package com.juyu.miliao.authentication.config;

import com.juyu.miliao.authentication.dao.redis.UserRedisDao;
import com.juyu.miliao.common.dataSource.key.DataSourceKeyEvaluator;
import com.juyu.miliao.common.exception.InternalServerErrorException;
import com.juyu.miliao.common.exception.ResourceNotFoundException;

public class GlobalDataSourceKeyEvaluator implements DataSourceKeyEvaluator{
	private UserRedisDao userRedisDao;

	public GlobalDataSourceKeyEvaluator(UserRedisDao userRedisDao){
		this.userRedisDao = userRedisDao;
	}
	
	@Override
	public String strategy(String strategy, Object param) {
		if("byUserId".equals(strategy)){
            return getDataSourceKeyByUserId((long) param);
		}else if("byUsername".equals(strategy)){
			return getDataSourceKeyByUserId(userRedisDao.getUserIdByUserName((String) param)
					.orElseThrow(() -> new ResourceNotFoundException("用户名不存在")));
		}else if("byOpenId".equals(strategy)){
			return getDataSourceKeyByUserId(userRedisDao.getUserIdByOpenId((String) param)
					.orElseThrow(() -> new ResourceNotFoundException("openId不存在")));
		}else
			throw new InternalServerErrorException("strategy 类型不支持：" + strategy);
	}

    private String getDataSourceKeyByUserId(long userId) {
        return "miliao-user-" + userId % 100;
	}
	
}
